package cn.iocoder.yudao.module.member.service.auth;

import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.*;
import cn.iocoder.yudao.module.member.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.system.api.logger.LoginLogApi;
import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.api.social.SocialClientApi;
import cn.iocoder.yudao.module.system.api.social.SocialUserApi;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.AppAuthEmailLoginReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import cn.iocoder.yudao.module.system.service.mail.MailLogService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_EMAIL_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_USERNAME_EXISTS;

/**
 * 会员的认证 Service 接口
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class MemberAuthServiceImpl implements MemberAuthService {

    @Resource
    private MemberUserService userService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private LoginLogApi loginLogApi;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private SocialClientApi socialClientApi;
    @Resource
    private OAuth2TokenApi oauth2TokenApi;
    @Resource
    private MailLogService mailLogService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private MemberUserService memberUserService;

    @Override
    public AppAuthLoginRespVO login(AppAuthLoginReqVO reqVO) {
        // 使用账号 + 密码，进行登录。

        AdminUserDO user = login0(reqVO.getUsername(), reqVO.getPassword());

        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, openid);
    }

    @Override
    public AppAuthLoginRespVO loginWithEmail(AppAuthEmailLoginReqVO reqVO) {
        AdminUserDO user = login1(reqVO.getEmail(), reqVO.getCode());
        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getEmail(), LoginLogTypeEnum.LOGIN_MOBILE, openid);
    }

    @Override
    @Transactional
    public AppAuthLoginRespVO smsLogin(AppAuthSmsLoginReqVO reqVO) {
        // 校验验证码
        String userIp = getClientIP();
        smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp));

        // 获得获得注册用户
        AdminUserDO user = adminUserService.createUserIfAbsent(reqVO.getMobile(), userIp, UserTypeEnum.CUSTOMER.getValue());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS, LoginResultEnum.USER_DISABLED);
            throw exception(ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED);
        }

//        // 如果 socialType 非空，说明需要绑定社交用户
        String openid = null;
        if (reqVO.getSocialType() != null) {
            openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }

//        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, reqVO.getMobile(), LoginLogTypeEnum.LOGIN_SMS, openid);
    }


    /**
     * 短信注册
     *
     * @param reqVO
     * @return
     */
    @Override
    public Boolean smsRegistry(AppAuthSmsRegistryVO reqVO) {
        AdminUserDO isUserExist = adminUserService.getUserByUsername(reqVO.getUsername());
        if (isUserExist != null) {
            // 如果用户名已存在，抛出异常
            throw exception(USER_USERNAME_EXISTS);
        }

        AdminUserDO isPhoneExist = adminUserService.getUserByMobile(reqVO.getMobile());
        if (isPhoneExist != null) {
            // 如果手机号已存在，抛出异常
            throw exception(ErrorCodeConstants.USER_MOBILE_EXISTS);
        }

        String userIp = getClientIP();

        //检验验证码
        smsCodeApi.useSmsCode(convert(reqVO, SmsSceneEnum.MEMBER_LOGIN.getScene(), userIp));
        return adminUserService.createUserIfAbsent(reqVO.getUsername(), reqVO.getPassword(), reqVO.getMobile(), UserTypeEnum.CUSTOMER.getValue()) != null;
    }


    @Override
    public AppAuthEmailRegistryVO mailRegistry(AppAuthEmailRegistryVO reqVO) {
        AdminUserDO isUserExist = adminUserService.getUserByUsername(reqVO.getUsername());
        if (isUserExist != null) {
            // 如果用户名已存在，抛出异常
            throw exception(USER_USERNAME_EXISTS);
        }
        AdminUserDO isEmailExit = adminUserService.getUserByEmail(reqVO.getEmail());
        if (isEmailExit != null) {
            // 如果邮箱已存在，抛出异常
            throw exception(USER_EMAIL_EXISTS);
        }
        String userIp = getClientIP();
        Integer scene = 0;
        // 检查验证码
        boolean isCodeValid = mailLogService.CheckCode(reqVO.getEmail(), reqVO.getCode(), scene);

        // 如果验证码有效
        if (isCodeValid) {
            // 调用 userService 创建用户
            boolean isUserCreated = userService.createEmailUser(reqVO.getUsername(), reqVO.getPassword(), reqVO.getEmail(), userIp);
            boolean useMailCode = mailLogService.userMailCode(reqVO.getEmail(), reqVO.getCode(), scene);
            if (isUserCreated) {
                // 创建用户成功，返回注册信息
                return reqVO;  // 根据需求你可以返回更详细的用户信息
            } else {
                // 用户创建失败
                throw new RuntimeException("用户创建失败");
            }
        } else {
            // 验证码错误，抛出异常或返回错误信息
            throw new RuntimeException("验证码无效或错误");
        }
    }


    @Override
    @Transactional
    public AppAuthLoginRespVO socialLogin(AppAuthSocialLoginReqVO reqVO) {
//        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
//        SocialUserRespDTO socialUser = socialUserApi.getSocialUserByCode(UserTypeEnum.MEMBER.getValue(), reqVO.getType(),
//                reqVO.getCode(), reqVO.getState());
//        if (socialUser == null) {
//            throw exception(AUTH_SOCIAL_USER_NOT_FOUND);
//        }
//
//        // 情况一：已绑定，直接读取用户信息
//        MemberUserDO user;
//        if (socialUser.getUserId() != null) {
//            user = userService.getUser(socialUser.getUserId());
//        // 情况二：未绑定，注册用户 + 绑定用户
//        } else {
//            user = userService.createUser(socialUser.getNickname(), socialUser.getAvatar(), getClientIP(), getTerminal());
//            socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
//                    reqVO.getType(), reqVO.getCode(), reqVO.getState()));
//        }
//        if (user == null) {
//            throw exception(ErrorCodeConstants.USER_NOT_EXISTS);
//        }
//
//        // 创建 Token 令牌，记录登录日志
//        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, socialUser.getOpenid());
        return null;
    }

    @Override
    public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) {
//        // 获得对应的手机号信息
//        SocialWxPhoneNumberInfoRespDTO phoneNumberInfo = socialClientApi.getWxMaPhoneNumberInfo(
//                UserTypeEnum.MEMBER.getValue(), reqVO.getPhoneCode());
//        Assert.notNull(phoneNumberInfo, "获得手机信息失败，结果为空");
//
//        // 获得获得注册用户
//        MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(),
//                getClientIP(), TerminalEnum.WECHAT_MINI_PROGRAM.getTerminal());
//        Assert.notNull(user, "获取用户失败，结果为空");
//
//        // 绑定社交用户
//        String openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
//                SocialTypeEnum.WECHAT_MINI_APP.getType(), reqVO.getLoginCode(), reqVO.getState()));
//
//        // 创建 Token 令牌，记录登录日志
//        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, openid);
        return null;
    }

    private AppAuthLoginRespVO createTokenAfterLoginSuccess(AdminUserDO user, String username,
                                                            LoginLogTypeEnum logType, String openid) {
        // 插入登陆日志
        createLoginLog(user.getId(), username, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        MemberUserDO memberUser = memberUserService.getUser(user.getId());
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                        .setUserId(user.getId()).setUserType(getUserType().getValue())
                        .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT)).setUsername(username)
                .setAvatar(user.getAvatar());

        // 构建返回结果
        AppAuthLoginRespVO respVO = AuthConvert.INSTANCE.convert(accessTokenRespDTO, openid);
        respVO.setAvatar(user.getAvatar());
        respVO.setUsername(user.getUsername());
        respVO.setSex(user.getSex());
        respVO.setMobile(user.getMobile());

        return respVO;
    }

    @Override
    public String getSocialAuthorizeUrl(Integer type, String redirectUri) {
        return socialClientApi.getAuthorizeUrl(type, UserTypeEnum.MEMBER.getValue(), redirectUri);
    }

    private AdminUserDO login0(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在

        AdminUserDO user = adminUserService.getUserByUsername(username);
        if (user == null) {
            throw exception(ErrorCodeConstants.USER_NOT_EXISTS);
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(ErrorCodeConstants.AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用`
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    private AdminUserDO login1(String email, String code) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_MOBILE;
        AdminUserDO user = adminUserService.getUserByEmail(email);
        if (user == null) {
            throw exception(ErrorCodeConstants.USER_NOT_EXISTS);
        }
        Integer scene = 1;
        boolean isCodeValid = mailLogService.CheckCode(email, code, scene);

        if (!isCodeValid) {
            createLoginLog(user.getId(), email, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(ErrorCodeConstants.SMS_CODE_NOT_FOUND);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            createLoginLog(user.getId(), email, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(ErrorCodeConstants.AUTH_LOGIN_USER_DISABLED);
        }
        boolean useMailCode = mailLogService.userMailCode(email, code, scene);
        return user;
    }


    private void createLoginLog(Long userId, String username, LoginLogTypeEnum logType, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(username);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogApi.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, getClientIP());
        }
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.removeAccessToken(token);
        if (accessTokenRespDTO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenRespDTO.getUserId());
    }

    @Override
    public void sendSmsCode(Long userId, AppAuthSmsSendReqVO reqVO) {

        if (Objects.equals(reqVO.getScene(), SmsSceneEnum.MEMBER_LOGIN.getScene())) {
            MemberUserDO user = userService.getUser(userId);
            // TODO 芋艿：后续 member user 手机非强绑定，这块需要做下调整；
            reqVO.setMobile(user.getMobile());
        }

        // 执行发送
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public void validateSmsCode(Long userId, AppAuthSmsValidateReqVO reqVO) {
        smsCodeApi.validateSmsCode(AuthConvert.INSTANCE.convert(reqVO));
    }

    @Override
    public AppAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenRespDTO accessTokenDO = oauth2TokenApi.refreshAccessToken(refreshToken,
                OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO, null);
    }

    private void createLogoutLog(Long userId) {
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(LoginLogTypeEnum.LOGOUT_SELF.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(getMobile(userId));
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogApi.createLoginLog(reqDTO);
    }

    private String getMobile(Long userId) {
        if (userId == null) {
            return null;
        }
        MemberUserDO user = userService.getUser(userId);
        return user != null ? user.getMobile() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.MEMBER;
    }


    private SmsCodeUseReqDTO convert(AppAuthSmsRegistryVO reqVO, Integer scene, String usedIp) {
        if (reqVO == null && scene == null && usedIp == null) {
            return null;
        }

        SmsCodeUseReqDTO smsCodeUseReqDTO = new SmsCodeUseReqDTO();

        if (reqVO != null) {
            smsCodeUseReqDTO.setMobile(reqVO.getMobile());
            smsCodeUseReqDTO.setCode(reqVO.getCode());
        }
        smsCodeUseReqDTO.setScene(scene);
        smsCodeUseReqDTO.setUsedIp(usedIp);
        return smsCodeUseReqDTO;
    }

}
